package com.flask.colorpicker.cameralibrary.util;

import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.media.camera.CameraKit;
import ohos.media.camera.device.CameraInfo;

/**
 * CameraParam Util
 */
public class CameraParamUtil {
    /**
     * Rotation constant: 0 degree rotation.
     */
    public static final int ROTATION_0 = 0;

    /**
     * Rotation constant: 90 degree rotation.
     */
    public static final int ROTATION_90 = 1;

    /**
     * Rotation constant: 180 degree rotation.
     */
    public static final int ROTATION_180 = 2;

    /**
     * Rotation constant: 270 degree rotation.
     */
    public static final int ROTATION_270 = 3;

    private static CameraParamUtil sCameraParamUtil = null;


    private CameraParamUtil() {
    }

    /**
     * get Instance
     *
     * @return CameraParamUtil
     */
    public static CameraParamUtil getInstance() {
        if (sCameraParamUtil == null) {
            sCameraParamUtil = new CameraParamUtil();
        }
        return sCameraParamUtil;
    }

    /**
     * getCameraDisplayOrientation
     *
     * @param context     Context
     * @param cameraId    int
     * @param orientation int
     * @return int
     */
    public int getCameraDisplayOrientation(Context context, int cameraId, int orientation) {
        CameraInfo info = CameraKit.getInstance(context).getCameraInfo(String.valueOf(cameraId));
        Display display = DisplayManager.getInstance().getDefaultDisplay(context).get();
        int rotation = display.getRotation();

        int degrees = 0;
        switch (rotation) {
            case ROTATION_0:
                degrees = 0;
                break;
            case ROTATION_90:
                degrees = 90;
                break;
            case ROTATION_180:
                degrees = 180;
                break;
            case ROTATION_270:
                degrees = 270;
                break;
        }
        int result;
        if (info.getFacingType() == CameraInfo.FacingType.CAMERA_FACING_FRONT) {
            result = (orientation + degrees) % 360;
            result = (360 - result) % 360;
        } else {
            // back-facing
            result = (orientation - degrees + 360) % 360;
        }
        return result;
    }
}
